package com.example.leetdemo.finash;

import java.util.*;

public class Solution846 {
    public boolean isNStraightHand(int[] hand, int groupSize) {
        if (hand.length % groupSize > 0) {
            return false;
        }
        Arrays.sort(hand);
        List<int[]> list = new ArrayList<>();
        for (int i = 0; i < hand.length; i++) {
            if (list.size() > 0 && list.get(list.size() - 1)[0] != hand[i]) {
                list.add(new int[] {hand[i], 1});
            } else if (list.size() > 0 && list.get(list.size() - 1)[0] == hand[i]) {
                int[] p = list.get(list.size() - 1);
                p[1] += 1;
                list.set(list.size() - 1, p);
            } else {
                list.add(new int[] {hand[i], 1});
            }
        }
        for (int i = 0; i < list.size() - groupSize + 1; i++) {
            int[] th = list.get(i);
            if (th[1] > 0) {
                for (int j = 1; j < groupSize; j++) {
                    int[] p = list.get(i + j);
                    if (p[0] != th[0] + j) {
                        return false;
                    } else {
                        p[1] -= th[1];
                        list.set(i + j, p);
                    }
                }
                th[1] = 0;
                list.set(i, th);
            }
        }
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i)[1] != 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Solution846 solution846 = new Solution846();
        System.err.println(solution846.isNStraightHand(new int[] {999,998,997,1000001,1000002,1000003}, 3));
    }
}
